package com.lfy.kcat.workflow.controller;

import lombok.extern.slf4j.Slf4j;
import org.camunda.bpm.engine.HistoryService;
import org.camunda.bpm.engine.RuntimeService;
import org.camunda.bpm.engine.TaskService;
import org.camunda.bpm.engine.history.HistoricVariableInstance;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.camunda.bpm.engine.spring.annotations.ProcessId;
import org.camunda.bpm.engine.task.Task;
import org.dromara.common.core.constant.CamundaConst;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.dto.DramaAuthManualTaskDTO;
import org.dromara.common.core.dto.DramaAuthStartDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 流程管理
 * @author leifengyang
 * @version 1.0
 * @date 2025/9/10 14:52
 * @description:
 */
@Slf4j
@RestController
public class ProcessManagerController {


    @Autowired
    RuntimeService runtimeService;
    @Autowired
    HistoryService historyService;
    @Autowired
    TaskService taskService;
    @GetMapping("/process/variables/{processId}")
    public R<Map<String,Object>> getProcessVariables(@PathVariable ("processId") String processId){
        //什么意思。为什么要获取ProcessInstance
        //这里获取实例id，singleResult是附加的，没有必要
        ProcessInstance processInstance = runtimeService
            .createProcessInstanceQuery()
            .processInstanceId(processId).singleResult();
        List<HistoricVariableInstance> list = historyService
            .createHistoricVariableInstanceQuery()
            .processInstanceId(processId).list();

        Map<String,Object> map = new HashMap<>();
        for (HistoricVariableInstance instance : list) {
            Object value = instance.getValue();
            String name = instance.getName();
            map.put(name,value);
        }
        return R.ok("success",map);
    }

        /**
     * 完成用户短剧审核任务
     * @return
     */
    @PutMapping("/process/authtask")
    public R claimManualAuthTaskAndComplete(
        @RequestBody DramaAuthManualTaskDTO dto
    ){//为啥匹配不到实例
        Task singleResult = taskService.createTaskQuery()
            .processInstanceId(dto.getProcessId())
            .singleResult();

        // 添加空值检查
        if (singleResult == null) {
            log.error("未找到匹配的人工审核任务，流程实例ID: {}", dto.getProcessId());
            return R.fail("未找到匹配的人工审核任务");
        }

        //让用户领任务
        taskService.claim(singleResult.getId(),dto.getUserName());

        boolean approve = false;
        //完成任务
        if ("1".equals(dto.getAuditStatus())) {
            approve = true;
        }

        Map<String,Object> variables = new HashMap<>();
        variables.put("approve",approve);
        variables.put("auditStatus",dto.getAuditStatus());
        variables.put("auditReason",dto.getAuditReason());
        variables.put("authStatus", dto.getAuditStatus());
        taskService.complete(singleResult.getId(),variables);
        log.info("人工任务完成....");

        return  R.ok();
    }


    /**
     * 启动短剧审核流程
     * @param
     * @return
     */
    @PostMapping("/process/start/dramaAuth")
    public R startDramaAuthProcess(@RequestBody DramaAuthStartDTO dramaAuthStartDTO){

        log.info("controller 准备启动短剧审核流程：{}", dramaAuthStartDTO);
        // 把DTO转成map
        Map<String,Object> vars = buildParamMap(dramaAuthStartDTO);

        ProcessInstance instance = runtimeService
            .startProcessInstanceByKey(
                CamundaConst.DRAMA_AUTH_PROCESS_DEFINITION_KEY,vars);

        return R.ok("success",instance.getId());
    }

    private Map<String, Object> buildParamMap(DramaAuthStartDTO dramaAuthStartDTO) {
        Map<String, Object> map = new HashMap<>();

        map.put("dramaName", dramaAuthStartDTO.getDramaName());
        map.put("description", dramaAuthStartDTO.getDescription());
        map.put("dramaId", dramaAuthStartDTO.getDramaId());
        return map;
    }

}
